<template>
  <el-dialog
    v-dialogDrag
    :visible="isDialogVisible"
    :title="titleName"
    width="70%"
    center
    :append-to-body="true"
    :close-on-click-modal="false"
    @close="closeEdit"
  >
    <dialogHeader slot="title" :title="titleName" :style-type="$store.state.app.dialogType" />
    <div class="filter-container filter-params">
      <one-table-template
        ref="multipleTable"
        :dynamic-api-config="dynamicApiConfig"
        :dynamic-buttons="dynamicButtons"
        :dynamic-components="tableComponents"
        :dynamic-table-cols="dynamicTableCols"
        :dynamic-form-fields="formField"
        :dynamic-is-show-more-btn="true"
        :dynamic-is-show-select="true"
        :dynamic-export-converts="dynamicExportConverts"
        :refresh-table-key="refreshTableKey"
      />
    </div>
  </el-dialog>
</template>

<script>
import dialogHeader from '@/components/dialogHeader'
import OneTableTemplate from '@/components/templates/oneTable'
import { orgApis } from '@/api/apiList/org'
// import { setDynamicFieldsData } from '@/utils/dataOperation'
// import { testApis } from '@/api/graphQLApiList/test'
import api from '@/api/vehicleManagement'
export default {
  components: {
    dialogHeader,
    OneTableTemplate
  },
  props: {
    isDialogVisible: {
      type: Boolean,
      default: false
    },
    dataForForm: {
      type: Object,
      default: () => {}
    },
    titleName: {
      type: String,
      default: ''
    }
  },
  data() {
    // 页面标识（与上面beforeRouteEnter中的对应）
    const viewPageCode = this.$route.path
    // 绑定事件配置化事件
    this.$ConfigCache.CacheConfig.bindEvent(this, [viewPageCode])
    return {
      // 验证
      valid: false,
      refreshTableKey: '0',
      editPopupsState: 'add',
      // table表格查询API配置对象
      dynamicApiConfig: orgApis.stoTransferInstructionQueryByPage,
      // 动态组件-查询条件
      tableComponents:
        this.$ConfigCache.CacheConfig.cacheData[viewPageCode] &&
        this.$ConfigCache.CacheConfig.cacheData[viewPageCode].tableComponents
          .length > 0
          ? this.$ConfigCache.CacheConfig.cacheData[viewPageCode]
            .tableComponents
          : [
            {
              compKey: 'compKey1',
              labelName: '选装包编码：',
              codeField: 'optionalPackCode',
              disabled: true,
              isRequire: true,
              component: () => import('@/components/org/commonInput'),
              type: 'inputText',
              isMust: true,
              span: 8
            },
            {
              compKey: 'compKey2',
              labelName: '选装包名称：',
              codeField: 'optionalPackName',
              lookuptype: 'DB0064',
              isRequire: true,
              component: () => import('@/components/org/commonInput'),
              type: 'inputText',
              isMust: true,
              span: 8
            },
            {
              compKey: 'compKey3',
              labelName: '状态：',
              codeField: 'isEnableCode',
              isRequire: true,
              component: () => import('@/components/org/isEnable/isEnableOne'),
              type: 'dropdownList',
              isMust: true,
              span: 8
            },
            {
              compKey: 'compKey4',
              labelName: '价格：',
              codeField: 'optionalPrice',
              isRequire: true,
              validrule: {
                // 保留一到两位小数
                /* isformat: /^([0-9]*)+(\.[0-9]{1,2})?$/, */
                isformat: /^([1-9]\d{0,10}|[1-9][0-9]{0,10}\.\d{1,2}|0\.\d{1,2}?|0)$/,
                resectMessage: {
                  isformat: '请输入正确的价格!'
                }
              },
              component: () => import('@/components/org/commonInput'),
              type: 'inputText',
              isMust: true,
              span: 8
            }
          ],
      // form 的表单对象
      formField: this.$utils.getFormField(
        this,
        {
          optionalPackCode: '',
          optionalPackName: '',
          isEnableCode: '1',
          optionalPrice: ''
          // updateControlId: this.dataForForm.updateControlId
        },
        this.$ConfigCache.CacheConfig.cacheData[viewPageCode]
      ),
      // 动态组件-按钮
      dynamicButtons:
        this.$ConfigCache.CacheConfig.cacheData[viewPageCode] &&
        this.$ConfigCache.CacheConfig.cacheData[viewPageCode].tableButtons &&
        this.$ConfigCache.CacheConfig.cacheData[viewPageCode].tableButtons
          .length > 0
          ? this.$ConfigCache.CacheConfig.cacheData[viewPageCode].tableButtons
          : [
            {
              compKey: 'btnKey1',
              type: 'primary',
              size: 'small',
              name: 'search',
              clickEvent: () => this.save(),
              text: '保存'
            },
            {
              compKey: 'btnKey2',
              type: '',
              size: 'small',
              icon: 'iconfont  icon-cancel',
              clickEvent: () => this.closeEdit(1),
              text: '取消'
            }
          ],
      // 动态组件-表格网格列
      dynamicTableCols:
        this.$ConfigCache.CacheConfig.cacheData[viewPageCode] &&
        this.$ConfigCache.CacheConfig.cacheData[viewPageCode].tableCols.length >
          0
          ? this.$ConfigCache.CacheConfig.cacheData[viewPageCode].tableCols
          : [],
      // 字段格式化转换（用于导出excel）（kvs表示键值转换）
      dynamicExportConverts: {
        isEnable: {
          convert: 'kvs',
          kvs: {
            '1': '是',
            '0': '否'
          }
        }
      },
      // 单表格模版页面组件回调事件
      callbackObj: {
        // 当选择项发生变化时会触发该事件（多选时）
        onCheckSelectChange: (selection) => {
          this.handleSelectionChange(selection)
        }
      }
    }
  },
  created() {
    this.formField = this.dataForForm
  },
  mounted() {
    // this.initData()
  },
  methods: {
    // form表单组件每个元素所占栅格栏数每行24格
    spanNum() {
      return 24
    },

    // 关闭弹窗
    closeEdit() {
      this.$emit('closeEdit', false)
    },

    // 保存
    save() {
      this.$utils.validataMoth(this, 'validpage')
      if (this.valid) {
        const { isEnableCode, optionalPackCode, optionalPackName, optionalPrice, updateControlId, optionalPackId, creator, creatorDate } = this.formField
        this.$requestAPI({
          apiUrl: api.vePackEdit.APIUrl,
          variables: { isEnableCode, optionalPackCode, optionalPackName, optionalPrice, updateControlId, optionalPackId, creator, creatorDate }
        }).then(res => {
          if (res.result === '1') {
            // 请求成功
            this.$message(res.msg)
            this.$emit('update:is-dialog-visible', false)
            this.$parent.$refs.multipleTable.queryTable(1)
          } else {
            this.$message(res.msg)
          }
        }).catch(err => {
          // 请求失败 错误提示
          this.$message(err.response.data.msg)
        })
      }
    }
  }
}
</script>

